package com.automannn.atm_back.modules.codeGenerator.core.service;

import cn.hutool.core.util.ZipUtil;
import com.automannn.atm_back.common.system.vo.LoginUser;
import com.automannn.atm_back.modules.codeGenerator.core.util.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;

/**
 * @author chenkh
 * @time 2020/8/6 8:42
 */
@Component
public class ZipCompressService implements CompressService{

    @Value("${atm_back.codeGenerate.tmpDir}")
    private String tmpDir;

    @Override
    public String getTmpDir() {
        return tmpDir;
    }

    @Override
    public File compress() {
        if(StringUtils.isEmpty(tmpDir)) throw new RuntimeException("压缩文件路径为空!");
        //todo: 将shiro的认证换位springSecurity的授权
       LoginUser loginUser= (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userTmpDir = tmpDir+ "_"+loginUser.getUsername();
        //兼容linux
        if(File.separator.equals("/")){
            try {
                String jar_parent = new File(ResourceUtils.getURL("classpath:").getPath()).getParentFile().getParentFile().getParent();
                userTmpDir =jar_parent+"/"+userTmpDir;
                System.out.println("linux代码路径："+userTmpDir);
            } catch (FileNotFoundException e) {
                throw new RuntimeException("系统错误，请联系管理员排查!");
            }

        }
//        File file = new File(userTmpDir);
//        if(!file.exists()){
//            throw new RuntimeException("文件路径不存在!");
//        }

        String zipFileName = userTmpDir+".zip";
        File zipFile=ZipUtil.zip(userTmpDir,zipFileName,true);
        return zipFile;
    }

    @Override
    public void syncRemote(URL url) {
        //todo: 后一步开发
    }
}
